 <template>
  <div class="bg_page upload_goods_page">
    <header-bar title="卖了换钱" v-if="sourceFrom != 'aishangjie'" :interceptReturn="true" @return="checkIfNeedSaveData"></header-bar>
    <!-- <pull-refresh :bottom="panelBottom" ref="pullRefreshPanel" :background-color="'#fff'" :top="sourceFrom == 'aishangjie'?0:headerHeight" :enableRefresh="true" @refresh="refreshData"> -->
      <div class="img_block">
        <img-list-upload v-if="finishInitImgList" ref="imgListUpload" :img-list.sync="imgList"></img-list-upload>
      </div>
      
      <div class="input_block">
        <div class="goods_title px1bb">
          <div class="goods_title_input pf_m" v-if="sourceFrom == 'aishangjie'">{{goodsName}}</div>
          <input class="goods_title_input pf_m" v-else v-model="goodsName" type="text" placeholder="请输入商品的名称和品牌型号" maxlength="50" @focus="inputFocus" @blur="inputBlur"/>
        </div>
        <div class="goods_detail">
          <div class="text_filled" contenteditable="true"><br/>{{goodsDescription || "简单描述下转手原因、入手渠道、新旧程度和使用感受吧~ (不少于5个字)"}}</div>
          <textarea class="goods_detail_input" v-model="goodsDescription" placeholder="简单描述下转手原因、入手渠道、新旧程度和使用感受吧~ (不少于5个字)" maxlength="200" @focus="inputFocus" @blur="inputBlur"></textarea>
        </div>
      </div>

      <div class="select_block">
        <ul class="select_list">
          <li class="select_item px1bb" @click="inputPricePanelShow = true">
            <img class="item_icon" src="~@/assets/imgs/common/upgoods_icon1.png">
            <div class="item_left">
              <span class="item_name">商品价格</span>
            </div>
            <div class="item_right">
              <div class="right_content pf_m" style="font-size:0.32rem;" v-show="sellingPrice"><span class="more_colse">￥</span>{{sellingPrice*1+''}}</div>
              <div class="right_content pf_m" v-show="sellingPrice && postage*1 > 0">+&nbsp;运费{{postage*1+''}}元</div>
          
              <img class="right_arrow" src="~@/assets/imgs/common/right_arrow_icon.png">
            </div>
          </li>
          <li class="select_item px1bb" @click="catePanelShow = true">
            <img class="item_icon" src="~@/assets/imgs/common/upgoods_icon2.png">
            <div class="item_left">
              <span class="item_name">商品分类</span>
            </div>
            <div class="item_right">
              <div class="right_content pf_m">{{goodsCate}}</div>
              <img class="right_arrow" src="~@/assets/imgs/common/right_arrow_icon.png">
            </div>
          </li>
          <li class="select_item px1bb" @click="showAddressPicker">
            <img class="item_icon" src="~@/assets/imgs/common/upgoods_icon3.png">
            <div class="item_left">
              <span class="item_name">所在位置</span>
            </div>
            <div class="item_right">
              <div class="right_content max5 pf_m">{{province}} {{city}} {{area}}</div>
              <img class="right_arrow" src="~@/assets/imgs/common/right_arrow_icon.png">
            </div>
          </li>
        </ul>

        <div class="goods_tags">
          <button class="tag_item" v-for="item in tagList" :key="item.id" :class="{'active':selectedTagList.indexOf(item.id+'') != -1}" @click="changeTags(item.id+'')">{{item.name}}</button>
        </div>

        <div class="submit_btn">
         <div class="agree_block">
            <img class="agree_icon" src="~@/assets/imgs/common/agree_icon_grey.png" v-show="!isAgree" @click="isAgree = true">
            <img class="agree_icon" src="~@/assets/imgs/common/agree_icon_green.png" v-show="isAgree" @click="isAgree = false">
            <div class="agree_text">确认已阅读并同意<span @click="toMgntRulesProtocol">《闲巢管理规则》</span></div>
          </div>
          <div class="btn btn_green" :class="{'disabled':btnDisabled}" @click="next">确认发布</div>
        </div>
      </div>
    
    <!-- </pull-refresh> -->

    <input-price-panel ref="inputPricePanel" :init-data="inputPricePanelInitData" :show.sync="inputPricePanelShow"  @close="closePricePanel" @commit="commitPricePanel"></input-price-panel>
    <cate-panel :show.sync="catePanelShow" @submit="getSelectedCate" :init-ids="cateIds" :init-names="cateNames"></cate-panel>
  </div>
</template>

<script>
import HeaderBar from "@/components/header.vue"
import PullRefresh from "@/components/pullRefresh.vue";
import {mapState,mapActions} from 'vuex';
import ImgListUpload from '@/views/common/imgListUpload/imgListUpload.vue';
import InputPricePanel from '@/views/common/inputPricePanel/inputPricePanel.vue';

import CatePanel from '@/views/common/catePanel/catePanel.vue'
import { provinceList, cityList, areaList } from '@/assets/js/area'
import native from '@/libs/native/index';
const addressData = provinceList
addressData.forEach(province => {
  province.children = cityList[province.value]
  province.children.forEach(city => {
    city.children = areaList[city.value]
  })
})


export default {
  props: {
   
  },
  components:{
    HeaderBar,
    PullRefresh,
    ImgListUpload,
    InputPricePanel,
    CatePanel
  },

  data() {
    return {
      panelBottom:0,

      imgList:[],
      goodsName:'',
      goodsDescription:'',
      sellingPrice:'',
      originalPrice:'',
      postage:'',
      categoryId:'',
      cateIds:[],
      cateNames:[],
      province:'',
      city:'',
      area:'',
      selectedTagList:[],
  
      inputPricePanelShow:false,
      catePanelShow:false,
      tagList:[],
    
      goodsCate:'',
      goodsId:'',

      categoryPathArr:[],

      finishInitImgList:false,
      sourceFrom:'',
      originType:'',
      specification:'',

      isFocusing:false,
      scrollTopFlag:0,
      isAgree:true,

      initPage:false,
      needReadCache:false
      // userPhone:''
    }
  },
  computed:{
    ...mapState({
      headerHeight: state => state.headerHeight,
      userInfo: state => state.user.userInfo
    }),

    inputPricePanelInitData(){
      return {
        sellingPrice: this.sellingPrice,
        originalPrice: this.originalPrice,
        postage:this.postage
      }
    },

    btnDisabled(){
      if(this.imgList.length == 0){
        return true;
      }
      if(!this.goodsName){
        return true;
      }
      if(this.goodsName.length < 5){
        return true;
      }
      if(!this.goodsDescription){
        return true;
      }
      if(this.goodsDescription.length < 5){
        return true;
      }
      if(!this.sellingPrice){
        return true;
      }
      if(!this.originalPrice){
        return true;
      }
      if(!this.categoryId){
        return true;
      }
      if(!this.province){
        return true;
      }
      return false;
    },
    hasDataFlag(){
      return this.imgList.length > 0 || this.goodsName || this.goodsDescription || this.sellingPrice || this.categoryId || this.province || this.selectedTagList.length > 0;
    }
  },

  beforeRouteEnter(to,from,next){
    next((vm)=>{
      if(from.name == 'mgntRulesProtocol'){
        vm.needReadCache = true;
      }else{
        vm.needReadCache = false;
      }
    });
  },

  mounted() {
    this.addressPicker = this.$createCascadePicker({
      title: '所在位置',
      data: addressData,
      onSelect: this.selectHandle,
      onCancel: this.cancelHandle
    });
    
    // let userInfoStr = sessionStorage.getItem('userInfo');
    // let userInfo = null;
    // if(userInfoStr){
    //   userInfo = JSON.parse(userInfoStr);
    //   this.userPhone = userInfo.phone;
    // };

    this.goodsId = this.$route.query.id || '';
    this.sourceFrom = this.$route.query.from || '';
    this.originType = this.$route.query.originType;
    if(this.sourceFrom == 'aishangjie'){
      this.$nextTick(()=>{
        if(this.needReadCache){
          this.initLocalStorageData(true);
        }else{
          this.getThirdGoodsInfo();
        }
      })
    }else if(this.goodsId){
      this.$nextTick(()=>{
        this.initPage = true;
        if(this.needReadCache){
          this.initLocalStorageData(true);
        }else{
          this.getGoodsInfo();
        }
      })
     
    }else{
      this.initPage = true;
      // 拿本地缓存里的数据
      this.initLocalStorageData();
    }
    this.getTagList();
  },

  methods: {
    ...mapActions(['toggleLoading','showMsg','showModal']),
    // 获取第三方里面的商品
    getThirdGoodsInfo(){
      let orderId = this.$route.query.orderId;
      this.toggleLoading({flag:true});
      this.$ajax.getThirdGoodsInfo({
        orderId:orderId
      }).then((res)=>{
         this.toggleLoading({flag:false});
        if(res.code=='0000'){
          let data = res.data;

          if(data.isRepeatPublish == 'Y'){
            this.$router.replace({
              name:'uploadGoodsResult',
              query:{
                from: this.sourceFrom,
                originType: this.originType,
              }
            });
            return;
          };
          
          this.initPage = true;
          if(data.imgUrls){
            let imgList = data.imgUrls.split(',')
            if(data.icon){
              imgList.unshift(data.icon);
            };
            this.imgList = imgList;
          }else{
            this.imgList = [];
          };
          this.finishInitImgList = true;
          this.goodsName = data.title;

          // this.goodsDescription = data.description;
          this.originalPrice = data.originalPrice || '';
          this.specification = data.specification;
          // this.province = data.province;
          // this.city = data.city;
          // this.area = data.region;
     
          // 初始化值
          this.$nextTick(()=>{
            this.$refs.inputPricePanel.initInputValue();
          });
        };
      });
    },
    // 获取闲巢里面的商品
    getGoodsInfo(done){
      if(!done){
        this.toggleLoading({flag:true});
      };
      this.$ajax.getGoodsInfo({
        id:this.goodsId
      }).then((res)=>{
         this.toggleLoading({flag:false});
        if(res.code=='0000'){
          let data = res.data;
          if(data.imgUrls){
            this.imgList = data.imgUrls.split(',');
          }else{
            this.imgList = [];
          };
          this.finishInitImgList = true;
          this.goodsName = data.title;
          this.goodsDescription = data.description;
          this.sellingPrice = data.price;
          this.originalPrice = data.originalPrice || '';
          this.postage = data.postage || '';
          this.province = data.province;
          this.city = data.city;
          this.area = data.region;
          this.selectedTagList = data.tagIds.split(',');

          this.categoryId = data.categoryId;
          
          // this.goodsCate = data.categoryNames;
          // this.cateIds = data.categoryIds.split('/')

          // 初始化值
          this.$nextTick(()=>{
            this.$refs.inputPricePanel.initInputValue();
          });
          this.categoryPathArr = [];

          this.getGoodsCatePath(data.categoryId);

          if(done){
            done();
          }
        };
      });
    },
    
    // 递归查询所属分类
    getGoodsCatePath(id){
      this.$ajax.getCateInfoById({
        id:id
      }).then((res)=>{
        if(res.code == '0000'){
           this.categoryPathArr.unshift(res.data);
           if(res.data.parentId != 0){
              this.getGoodsCatePath(res.data.parentId);
           }else{
              this.initGoodsCate();
           }
        }
      });
    },

    initGoodsCate(){
      let cateIds =[];
      let cateNames = [];
      this.categoryPathArr.forEach(item=>{
        cateIds.push(item.id);
        cateNames.push(item.name);
      });
      this.cateIds = cateIds;
      this.cateNames = cateNames;
      this.goodsCate = cateNames.join('/');
    },

    refreshData(done){
      if(this.goodsId){
        this.getGoodsInfo(done)
      }else{
        setTimeout(()=>{
          done();
        },600)
      }
    },

    showAddressPicker() {
      this.addressPicker.show()
    },

    selectHandle(selectedVal, selectedIndex, selectedText) {
      this.province = selectedText[0];
      this.city = selectedText[1];
      this.area = selectedText[2];
    },
    cancelHandle() {
     
    },
    closePricePanel(){
      this.inputPricePanelShow = false;
    },
    commitPricePanel(data){
      this.sellingPrice = data.sellingPrice;
      this.originalPrice = data.originalPrice;
      this.postage = data.postage;
      this.closePricePanel();
    },
    changeTags(i){
      let index = this.selectedTagList.indexOf(i);
      if(index != -1){
        this.selectedTagList.splice(index,1);
      }else{
        if(this.selectedTagList.length >= 3){
          this.showMsg({content:'最多选择三个标签'});
        }else{
          this.selectedTagList.push(i);
        }
      }
    },

    next(){
      this.$refs.imgListUpload.emitImgsData();
      this.submitData();
    },

    getSelectedCate(cateIds,cateNames){
      this.categoryId = cateIds.pop();
      this.goodsCate = cateNames.join('/');
    },

    // 获取商品标签
    getTagList(){
      this.$ajax.getTagList({}).then((res)=>{
        if(res.code=='0000'){
          this.tagList = res.data;
        }
      });
    },
    // 提交发布商品
    submitData(){
      console.log(this.imgList);
      let flag = this.checkData();
      if(!flag){
        return;
      }
      this.filterSeletedTags();
      this.toggleLoading({flag:true});
      this.$ajax.uploadGoods({
        id: this.goodsId,
        icon:this.imgList[0],
        imgUrls:this.imgList.join(','),
        title: this.goodsName,
        description: this.goodsDescription,
        sourceType:1, // 官方发布0，用户发布1
        price: this.sellingPrice*1+'',
        originalPrice: this.originalPrice ? this.originalPrice*1 + '':'',
        postage: this.postage?this.postage*1 + '':0,
        categoryId:this.categoryId,
        tagIds: this.selectedTagList.join(','),
        province: this.province,
        city: this.city,
        region: this.area,
        thirdOriOrderId: this.sourceFrom == 'aishangjie'?this.$route.query.orderId:'',
        specification:this.specification,
        source: this.sourceFrom == 'aishangjie'?'ishangjie':'xianchao', // 爱上街aishangjie，闲巢xianchao
      }).then((res)=>{
        this.toggleLoading({flag:false});
        if(res.code=='0000'){
          //成功清除数据
          localStorage.removeItem('tempUpLoadGoodsData'+ this.userInfo.phone);
          localStorage.removeItem('upLoadGoodsData' + this.userInfo.phone)
          this.$router.replace({
            name:'uploadGoodsResult',
            query:{
              from: this.sourceFrom,
              originType: this.originType,
              id: res.data
            }
          })
        }
      });
    },

    // 过滤去除失效的标签
    filterSeletedTags(){
      let selectedTagList = [];
    
      this.tagList.forEach((item)=>{
        this.selectedTagList.forEach((t)=>{
          if(item.id == t){
            selectedTagList.push(t);
          }
        })
      });
      this.selectedTagList = selectedTagList;
    },

    checkData(){
      console.log(this.imgList)
      if(!this.isAgree){
        this.showMsg({content:'请确认已阅读并同意《闲巢管理规则》'});
        return false;
      }
      if(this.imgList.length == 0){
        this.showMsg({content:'请至少上传一张商品图片'});
        return false;
      }
      if(!this.goodsName){
        this.showMsg({content:'请输入商品标题'});
        return false;
      }
       if(this.goodsName.length < 5){
        this.showMsg({content:'商品标题请至少输入5个字'});
        return false;
      }
      if(!this.goodsDescription){
        this.showMsg({content:'请输入商品描述'});
        return false;
      }
      if(this.goodsDescription.length < 5){
        this.showMsg({content:'商品描述请至少输入5个字'});
        return false;
      }
      
      if(!this.sellingPrice){
        this.showMsg({content:'请输入商品价格'});
        return false;
      }
      if(!this.originalPrice){
        this.showMsg({content:'请输入商品入手价格'});
        return false;
      }
      if(!this.categoryId){
        this.showMsg({content:'请选择商品分类'});
        return false;
      }
      if(!this.province){
        this.showMsg({content:'请选择所在位置'});
        return false;
      };
      return true;
    },

    checkIfNeedSaveData(){
      if(!this.goodsId && this.hasDataFlag){
        this.showModal({
          showClose:true,
          content: "是否保存填写的内容？",
          btns: ["不保存","保存" ],
          callbacks: [this.noSaveData,this.saveData]
        });
      }else{
        this.goBack();
      };
    },

    // 获取用户 先前保存的数据
    initLocalStorageData(cleanFlag){
      let upLoadGoodsData = '';
      if(this.sourceFrom == 'aishangjie' || this.goodsId){
        upLoadGoodsData = localStorage.getItem('tempUpLoadGoodsData' + this.userInfo.phone);
      }else{
        upLoadGoodsData = localStorage.getItem('upLoadGoodsData' + this.userInfo.phone);
      }
      if(upLoadGoodsData){
        try {
          let data = JSON.parse(upLoadGoodsData);
          let newTime = +new Date();
          
          // 缓存3天
          if(newTime - data.creatTime > 24*60*60*1000*3){
            this.finishInitImgList = true;
            localStorage.removeItem('upLoadGoodsData'+ this.userInfo.phone);
            return;
          };
          
          this.imgList = data.imgList;
          this.goodsName = data.goodsName;
          this.goodsDescription = data.goodsDescription;
          this.sellingPrice = data.sellingPrice;
          this.originalPrice = data.originalPrice;
          this.postage = data.postage || 0;
          this.province = data.province;
          this.city = data.city;
          this.area = data.area;
          this.selectedTagList = data.selectedTagList;
          this.$nextTick(()=>{
            this.$refs.inputPricePanel.initInputValue();
          });
          this.categoryId = data.categoryId;
          this.categoryPathArr = [];
          if(data.categoryId){
            this.getGoodsCatePath(data.categoryId);
          }
        } catch (error) {
          this.finishInitImgList = true;
          this.showMsg({content:'获取保存信息失败，请重新填写'});
        };
        if(cleanFlag){
          localStorage.removeItem('tempUpLoadGoodsData'+ this.userInfo.phone);
        }
      };
      this.finishInitImgList = true;
    },

    storageData(){
      let dataObj = {
        imgList: this.imgList,
        goodsName: this.goodsName,
        goodsDescription: this.goodsDescription,
        sellingPrice: this.sellingPrice,
        originalPrice: this.originalPrice,
        postage: this.postage,
        categoryId: this.categoryId,
        province: this.province,
        city: this.city,
        area: this.area,
        selectedTagList: this.selectedTagList,
        creatTime: + new Date()
      };
      if(this.sourceFrom == 'aishangjie' || this.goodsId){
        localStorage.setItem('tempUpLoadGoodsData' + this.userInfo.phone,JSON.stringify(dataObj));
      }else{
        localStorage.setItem('upLoadGoodsData' + this.userInfo.phone,JSON.stringify(dataObj));
      }
    },
    removeData(){
      localStorage.removeItem('tempUpLoadGoodsData'+ this.userInfo.phone);
      localStorage.removeItem('upLoadGoodsData' + this.userInfo.phone);
    },

    saveData(){
      this.storageData();
      this.goBack();
    },

    noSaveData(){
      this.removeData();
      this.goBack();
    },

    goBack(){
      if(this.originType == 'h5'){
        this.$router.go(-1);
      }else{
        native.closeWebPage();
      }
    },
    inputFocus() {
        this.isFocusing = true;
    },
    inputBlur() {
        this.isFocusing = false;
    },
    toMgntRulesProtocol(){
      this.storageData();
      this.$router.push({name:'mgntRulesProtocol',query:{
        originType:'h5',
        sourceFrom:this.sourceFrom
      }
      });
    }
  },
  watch:{
    isFocusing: function (val) {
        if (val) {
            this.scrollTopFlag = document.body.scrollTop;
        } else {
            document.body.scrollTop = this.scrollTopFlag;
        }
    }
  }
}
</script>

<style lang="less" scoped>

.bg_page{
  min-height: 100%;
  // background-color: #f6f6f6;
  background-color: #fff;
}

.img_block{
  padding:0.4rem 0 0.1rem 0.24rem;
  background-color: #fff;
  border-bottom:0.2rem solid #F6F6F6;
  min-height: 2.4rem;
}

.input_block{
  background-color: #fff;
  // padding:0 0.2rem;
  margin:0 0.24rem;
  padding-bottom: 0.32rem;
  // border-bottom:0.2rem solid #F6F6F6;
  .goods_title{
    display: flex;
    align-items: center;
    // height: 0.96rem;
    // border-bottom: 0.02rem solid #DDD;
    padding:0.24rem 0;
    &.px1bb{
        &::after{
            background-color: #eee;
        }
    }
    .goods_title_input{
      width: 100%;
      font-size: 0.32rem;
      color: #333;
      line-height: 0.4rem;

      &::-webkit-input-placeholder { /* Chrome/Opera/Safari */ 
		  	color: #CCC;
		  }
		  &::-moz-placeholder { /* Firefox 19+ */  
		  	color: #CCC;
		  }
		  &:-ms-input-placeholder { /* IE 10+ */ 
		   color: #CCC;
		  }
		  &:-moz-placeholder { /* Firefox 18- */ 
		   color: #CCC;
		  }

    }
  }
  .goods_detail{
    margin-top: 0.2rem;
    position: relative;

    .text_filled{
      font-size: 0.28rem;
      line-height: 0.4rem;
      color: #666;
      white-space: pre-wrap;
      min-height: 0.32rem;
    }
    .goods_detail_input{
      background-color: #fff;
      position: absolute;
      height: 100%;
      width: 100%;
      left: 0;
      top: 0;
      font-size: 0.28rem;
      line-height: 0.4rem;
      color: #666;
      resize:none;
      &::-webkit-input-placeholder { /* Chrome/Opera/Safari */ 
		  	color: #CCC;
		  }
		  &::-moz-placeholder { /* Firefox 19+ */  
		  	color: #CCC;
		  }
		  &:-ms-input-placeholder { /* IE 10+ */ 
		   color: #CCC;
		  }
		  &:-moz-placeholder { /* Firefox 18- */ 
		   color: #CCC;
		  }
    }
  }
}

.select_block{
  background-color: #fff;
  border-top:0.2rem solid #F6F6F6;
  .select_list{
    // padding:0 0.3rem;
    margin:0 0.24rem;
    .select_item{
      height: 0.96rem;
      display: flex;
      align-items: center;
      justify-content: space-between;
      // border-bottom: 0.02rem solid #DDD;
      position: relative;
       margin-left: 0.52rem;
      &.px1bb{
          &::after{
              background-color: #eee;
          }
      }
      .item_icon{
        position: absolute;
        left: -0.52rem;
        top: 0.3rem;
        width: 0.36rem;
        height: 0.36rem;
        margin-right: 0.16rem;
      }
      .item_left{
        display: flex;
        align-items: center;
        
        .item_name{
          font-size: 0.28rem;
          color: #333;
          line-height: 0.4rem;
        }
      }
      .item_right{
        display: flex;
        align-items: center;
        .right_content{
          color: #333;
          font-size: 0.28rem;
          line-height: 0.4rem;
          margin-right: 0.1rem;
          &.max5{
            max-width: 4.5rem;
            text-overflow: ellipsis;
            overflow: hidden;
            white-space: nowrap;
          }
          .more_colse{
            margin-right: -0.05rem;
          }
        }
        .right_arrow{
          width: auto;
          height: 0.24rem;
        }
      }
    }
  }
}

.goods_tags{
  display: flex;
  flex-wrap: wrap;
  padding:0.24rem;
  padding-bottom:0.1rem;
  background-color: #fff;
  .tag_item{
     height: 0.48rem;
     border-radius: 0.24rem;
     padding:0 0.2rem;
     background-color: #eee;
     color: #999;
     font-size: 0.24rem;
     margin-right: 0.2rem;
     margin-bottom: 0.2rem;
     white-space: nowrap;
     &.active{
       background-color: #E7F9F1;
       color: #14C878;
     }
  }
}
.submit_btn{
  margin:0 0.8rem;
  margin-top: 1.2rem;
  padding-bottom: 0.8rem;
  .agree_block{
    display: flex;
    align-items: center;
    justify-content: center;
    padding-bottom: 0.2rem;
    .agree_icon{
      width: 0.3rem;
      height: 0.3rem;
    }
    .agree_text{
      margin-left: 0.1rem;
      font-size: 0.22rem;
      color: #999;
      span{
        color: #666;
      }
    }
  }
}
</style>
